<template>
	<view>
		<view class="bg-header-container">
			<image class="bg-image" src="/static/my-back.png"></image>
			<!-- 登录中的状态 -->
			<view class="header-container" v-if="loginFlag" @click="toMineInfo">
				<image class="header-image" :src="userInfo.header"></image>
				<text class="user-name">{{ userInfo.nickname }}</text>
				<text class="header-text">By:闲言</text>
			</view>
			<!-- 非登录状态 -->
			<!-- #ifdef MP-WEIXIN -->
			<!-- 只有微信小程序可以使用 -->
			<button v-if="!loginFlag" open-type="getUserInfo" @getuserinfo="register" class="not-login-container">
				<view class="not-login-header"><image class="not-login-header-image" src="/static/icons/mine.png"></image></view>
				<view class="not-login-info">
					<text class="login">登录</text>
					<text class="login-line">|</text>
					<text class="register">注册</text>
				</view>
			</button>
			<!-- #endif -->
			<!-- #ifndef MP-WEIXIN -->
			<!-- 非微信小程序 -->
			<view v-if="!loginFlag" class="not-login-container" @click="toLogin">
				<view class="not-login-header"><image class="not-login-header-image" src="/static/icons/mine.png"></image></view>
				<view class="not-login-info">
					<text class="login">登录</text>
					<text class="login-line">|</text>
					<text class="register">注册</text>
				</view>
			</view>
			<!-- #endif -->
		</view>
	</view>
</template>
<!-- wx11d9020f78ab2066 -->
<script>
import userApi from '@/api/myUser.js'
export default {
	data() {
		return {
			// 获取user
			userInfo: uni.getStorageSync('user')
		};
	},
	props: ['loginFlag'],
	methods: {
		// 先注册，在登录
		register(e) {
			// 获取用户信息
			// 获取用户信息
			const userInfo = e.detail.userInfo;
			console.log(e);
			uni.login({
				provider: 'weixin',
				success(res) {
					const code = res.code;
					console.log(code+"111")
					// 从微信账号中获取信息
					const registerUser = {
						header: userInfo.avatarUrl,
						"sex": userInfo.gender,
						nickname: userInfo.nickName,
						code: code
					};
					userApi.registerWeixin(registerUser).then(res => {
						// token存储到本地缓存，user存储到本地缓存
						uni.setStorage({
							key:"user",
							data: res.data.user
						});
						uni.setStorage({
							key:"Authorization",
							data: res.data.token
						});
						const validateLogin = res.data.validateLogin;
						if(validateLogin==="0"){
							// 登录
							// 跳转到首页
							uni.reLaunch({
								url: '/pages/mine/mine'
							});
						}else{
							// 注册
							// 跳转到完善账号密码页面
							uni.navigateTo({
								url: '/pages/set-username/set-username'
							});
						}
					})
				}

			});
		},
		// 跳转到非微信小程序登录
		toLogin() {
			uni.navigateTo({
				url: '/pages/login/login'
			})
		},
		// 跳转到个人信息
		toMineInfo() {
			uni.navigateTo({
				url: '/pages/mine-info/mine-info'
			})
		}
	}
};
</script>

<style>
@import url('./index.css');
</style>
